import React, { useCallback, useState, useEffect, useMemo } from 'react';
// import type { UploadProps } from 'antd';
import { Button, Modal, Radio, Form, Input, Switch, Space, Upload, message, Spin } from 'antd';
import { AddIndexLibrary } from '../../../SearchResultEngine/designer/components/addIndexLibrary'; // 添加索引库组件
import PageSelect from '@inbiz/basic/PageSelect';
import { useForm } from '@formily/react';
import './DmsSetting/styles.less';
import style1Img from './assets/style1.svg';
import style2Img from './assets/style2.svg';
import { TextWidget, getMessage } from '@inbiz/react';
import MultilingualInput from '@inbiz/basic/MultilingualInput';
import { InfoCircleOutlined } from '@ant-design/icons';
import { getPlatform } from '@inbiz/utils';
import { UpdateTemplateFile } from '../service'
import UploadTemplate from './DmsSetting/UploadTemplate'
export interface IAddIndexRangeProps {
  value?: string;
  visible: boolean;
  currentData?: any;
  onOk?: (value: string) => void;
  onCancel?: () => void;
  onChange?: (value: string) => void;
}

// 随机生成标签编号
const guid = () => {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == 'x' ? r : (r & 0x3) | 0x8;
    return v.toString(16);
  });
};

export const AddIndexRange: React.FC<IAddIndexRangeProps> = (props) => {
  const [form] = Form.useForm();
  const { appInfo } = useForm() as unknown as { appInfo: { appId: string } };
  let { currentData } = props;

  const [isOpenAdvancedSearch, $isOpenAdvancedSearch] = useState(currentData?.advancedSearch); // 是否开启高级搜索
  const [addIndexLibraryModal, $addIndexLibraryModal] = useState(false); // 是否打开添加索引库弹窗
  const [indexLibraries, $indexLibraries] = useState(currentData?.indexLibraries || []); // 关联索引库

  const [guidInput, $guidInput] = useState(currentData?.guid || guid()); // 标签编号
  const [visible, $visible] = useState(false);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    $visible(props.visible);
  }, [props.visible]);

  useEffect(() => {
    if (!currentData?.quikSearchTemplate && currentData?.title?.includes('folder')) {
      form.setFieldsValue({
        quikSearchTemplate: 'folder.jsx',
        filepath: InbizConfig.PUBLIC_PATH + 'template/folder.jsx',
      })
    }
    if (!currentData?.quikSearchTemplate && currentData?.title?.includes('file')) {
      form.setFieldsValue({
        quikSearchTemplate: 'file.jsx',
        filepath: InbizConfig.PUBLIC_PATH + 'template/file.jsx',
      })
    }
  }, [currentData])
  // 弹窗保存事件
  const handleOk = useCallback(() => {
    form.validateFields().then((values) => {
      values.guid = values.guid || guidInput;
      if (!currentData) {
        // 新增
        values.isShow = true;
        values.isEdit = true;
        values.isDelete = true;
      } else {
        // 编辑
        values.isShow = currentData.isShow;
        values.isEdit = currentData.isEdit;
        values.isDelete = currentData.isDelete;
        values.isAll = currentData.isAll;
        values.isFile = currentData.isFile;
        values.isFolder = currentData.isFolder;
      }

      // 赋值
      props.onOk && props.onOk({ ...currentData, ...values });
      // 重置表单
      form.resetFields();
    });
  }, [props.onOk]);

  // 弹窗取消事件
  const handleCancel = () => {
    // 重置表单
    form.resetFields();
    $isOpenAdvancedSearch(false);
    props.onCancel && props.onCancel();
  };

  // 点击开启高级搜索开关触发事件
  const onOpenAdvancedSearch = (checked: boolean) => {
    $isOpenAdvancedSearch(checked);
    form.setFieldValue('advancedSearchStyle', 'style2')
  };

  // 选择关联索引库按钮点击事件
  const onAssociatedIndex = (event) => {
    $addIndexLibraryModal(true);
  };
  //  添加索引库组件的保存事件
  const onAddIndexSave = (values) => {
    $addIndexLibraryModal(false);
    $indexLibraries(values);
    form.setFieldsValue({
      indexLibraries: values,
    });
  };

  // 添加索引库组件的取消事件
  const onAddIndexCancel = () => {
    $addIndexLibraryModal(false);
  };

  // 添加索引库组件的配置参数
  const addIndexLibraryPops = {
    visible: addIndexLibraryModal,
    onSave: onAddIndexSave, // 选中事件
    onCancel: onAddIndexCancel, // 取消事件
    select: indexLibraries, // 选中的key
  };
  const indexLibrariesNames = useMemo(() => {
    return indexLibraries ? indexLibraries.map((item: any) => item.IndexName).join(',') : [];
  }, [indexLibraries]);
  // const onUploadTemplate = (event: ChangeEvent<HTMLInputElement>) => {
  //   let file = event.target.files?.[0]; //获取文件对象
  //   //检测是否是拖拽文件到页面的操作
  //   if (file) {
  //     UpdateTemplateFile(appInfo.appId, file)
  //       .then((res) => {
  //         file?.name ? message.success('更新成功') : message.success('导入成功');
  //       })
  //   }
  // }


  return (
    <div>
      <Modal
        title={
          !currentData
            ? getMessage('SearchEngine.addSearchRange')
            : getMessage('SearchEngine.editSearchRange')
        }
        visible={visible}
        onOk={handleOk}
        onCancel={handleCancel}
        cancelText={getMessage('SearchEngine.cancel')}
        okText={getMessage('SearchEngine.determine')}
        width={800}
        zIndex={5}
      >
        <Spin spinning={loading}>
          <Form
            form={form}
            name="dmsSetting"
            initialValues={{
              advancedSearchStyle: 'style2',
              ...currentData,
              guid: guidInput,
            }}
            autoComplete="off"
            className="search-dms-setting-wrapper"
          >
            <Form.Item
              label={getMessage('SearchEngine.labelName')}
              name="title"
              rules={[
                { required: true, message: getMessage('SearchEngine.tips.pleaseEnterTheLabelName') },
              ]}
            >
              <MultilingualInput placeholder={getMessage('SearchEngine.tips.pleaseEnterTheLabelName')} />
            </Form.Item>
            <Form.Item label={getMessage('SearchEngine.tagNumber')} name="guid">
              <Input disabled={!!currentData?.guid} />
            </Form.Item>
            {!currentData.isAll && !currentData.isFile && !currentData.isFolder && (
              <Form.Item
                label={getMessage('SearchEngine.associatedIndexLibrary')}
                name="indexLibraries"
                rules={[
                  {
                    required: true,
                    message: getMessage('SearchEngine.tips.pleaseSelectAnAssociatedIndexLibrary'),
                  },
                ]}
              >
                <Form.Item style={{ display: 'inline-block', marginBottom: '0' }}>
                  <Input value={indexLibrariesNames} disabled placeholder={getMessage('SearchEngine.tips.pleaseSelectAnAssociatedIndexLibrary')}/>
                </Form.Item>
                <Form.Item style={{ display: 'inline-block', marginBottom: '0' }}>
                  <Button className="indexLibrariesBtn" type="primary" onClick={onAssociatedIndex}>
                    <TextWidget>SearchEngine.choice</TextWidget>
                  </Button>
                </Form.Item>
              </Form.Item>
            )}

            {getPlatform() === 'web' && (
              <Form.Item
                name="imgSearchImg"
                label={getMessage('SearchEngine.imgSearchImg')}
                tooltip={{
                  title: getMessage('SearchEngine.imgSearchTips'),
                  icon: <InfoCircleOutlined />,
                }}
                valuePropName='checked'
              >
                <Switch />
              </Form.Item>
            )}

            {getPlatform() === 'web' && (
              <Form.Item name="keywordAtlas" valuePropName='checked' label={getMessage('SearchEngine.keywordAtlas')}>
                <Switch />
              </Form.Item>
            )}

            {getPlatform() === 'web' && (
              <>
                {currentData.viewType != 'smallPanelView' && <Form.Item label={getMessage('SearchEngine.searchBy')} name="searchMode">
                  <Switch defaultChecked={currentData?.searchMode} />
                </Form.Item>}
                {currentData.isAll != true && (
                  <Form.Item
                    label={getMessage('SearchEngine.advancedSearch')}
                    name="advancedSearch"
                    valuePropName="checked"
                  >
                    <Switch
                      onChange={onOpenAdvancedSearch}
                    />
                  </Form.Item>
                )}
              </>
            )}


            {isOpenAdvancedSearch && getPlatform() === 'web' && !currentData.isAll && currentData.viewType != 'smallPanelView' && (
              <Form.Item
                label={getMessage('SearchEngine.advancedSearchStyle')}
                name="advancedSearchStyle"
              >
                <Radio.Group className="advancedSearchStyle" >
                  <div className="advancedSearchStyle-item">
                    <Radio value="style1">
                      <img src={style1Img} />
                    </Radio>
                  </div>
                  <div className="advancedSearchStyle-item">
                    <Radio value="style2">
                      <img src={style2Img} />
                    </Radio>
                  </div>
                </Radio.Group>
              </Form.Item>
            )}

            {isOpenAdvancedSearch && !currentData.isAll && (
              <Form.Item
                label={getMessage('SearchEngine.associateAdvancedSearchPage')}
                name="associateAdvancedSearchPage"
                className="associateAdvancedSearchPage"
                rules={[
                  {
                    required: true,
                    message: getMessage(
                      'SearchEngine.tips.pleaseSelectTheAssociatedAdvancedSearchPage',
                    ),
                  },
                ]}
              >
                <PageSelect />
              </Form.Item>
            )}

            {getPlatform() === 'web' && currentData.viewType == 'smallPanelView' && (
              <UploadTemplate
                form={form}
                currentData={currentData}
                setLoading={setLoading}
              />
            )}


          </Form>
        </Spin>
      </Modal>
      <AddIndexLibrary {...addIndexLibraryPops} appId={appInfo.appId} />
    </div>
  );
};
